<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 14-5-15
 * Time: 下午11:39
 */
namespace ulue\parts;

use Ulue;
use ulue\core\utils\UseObjectAsArray;

class Cookie extends UseObjectAsArray
{
    public $expire;             //cookie存储时间
    public $cookieName;         //原始cookie名
    public $encryptCookieName;  //加密后的cookie名
    public $httpOnly;          // 设置 http only 

    /**
     * @param $cookieName
     * @param $cookieValue
     * @param bool $type cookie名是否加密
     * @param string $expire
     * @param null|string $path
     * @param null $domain
     * @param null $secure
     * @param null $httpOnly
     * @return bool
     */
    public function set(
        $cookieName, $cookieValue, $type=null,   $expire=null,
        $path='/',   $domain=null, $secure=null, $httpOnly=null
    ) {
        if ( empty($cookieName) )
        {
            return false;
        }

        if (is_string($cookieName)) {
            $this->cookieName = $cookieName;
            $type             = is_null($type) ?
                                Ulue::$app->get('cookie_name_encrypt') :
                                true;

            if ($type){
                $this->encryptCookieName = $cookieName = $this->encryption($cookieName);
            }

            !isset($_COOKIE[$cookieName]) || $this->remove($cookieName);//先删除原来同名的cookie
            //加密cookie值
            $cookieValue  = $this->encryption($cookieValue);
            $expire       = empty($expire) ? Ulue::$app->get('cookie.life_time'): $expire;
            $this->expire = time()+$expire*3600;
            setcookie($cookieName,$cookieValue,$this->expire,$path,$domain,$secure , $httpOnly);
        } else {
            return false;
        }
        return true;
    }

    /**
     * @param null $cookieName
     * @param bool $type cookie名是否加密过
     * @return bool
     */
    public function get($cookieName=Null,$type=false)
    {
        if (is_null($cookieName))
        {
            return $_COOKIE;
        }

        if (is_string($cookieName))
        {
            if ($type){
                $cookieName = $this->encryption($cookieName);
            }
            return isset($_COOKIE[$cookieName])?$_COOKIE[$cookieName]:false;
        }

        return false;

    }

    //todo 待改进。 已改，效果未知
    public function remove($cookieName=null)
    {
        if (is_null($cookieName))
        {
            $cookieName = $this->cookieName;
        }

        //存在 以原始cookie名 的cookie
        if ($this->get($cookieName,false) != false){
            setcookie($cookieName,'','-1');
            unset($_COOKIE[$cookieName]);
        }

        //存在 以原始cookie名称加密后的cookie名 的cookie
        if ($this->get($cookieName = $this->encryption($cookieName)) != false)
        {
            setcookie($cookieName,'','-1');
            unset($_COOKIE[$cookieName]);
        }

    }

    public function setHttpOnly($value=true)
    {
        $this->httpOnly = (bool) $value;
    }


}